﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication35
{

    enum LightColor
    {
        Undefined,
        Red,
        Yellow,
        Green
    }

    class LightColorChangedEventArgs : EventArgs
    {
        public LightColorChangedEventArgs (LightColor beforeColor, LightColor currentColor)
        {
            BeforeColor = beforeColor;
            CurrentColor = currentColor;
        }

        public LightColor BeforeColor { get; private set; }

        public LightColor CurrentColor { get; private set; }
    }

    class TrafficLight
    {
        private int _redDelay;
        private int _yellowDelay;
        private int _greenDelay;
        private Timer _timer;
        private int _counter;
        private LightColor _beforeColor;

        public TrafficLight(LightColor initialColor, int redDelay, int yellowDelay, int greenDelay)
        {
            CurrentColor = initialColor;
            _redDelay = redDelay;
            _yellowDelay = yellowDelay;
            _greenDelay = greenDelay;
            _timer = new Timer(CheckTime, null, 0, 1000);
            _counter = 0;
        }
        
        private void CheckTime(object o)
        {
            _counter++;
            if (CurrentColor == LightColor.Green && _counter == _greenDelay)
            {
                OnLightColorChanged(new LightColorChangedEventArgs(CurrentColor, LightColor.Yellow));
                _counter = 0;
            }
            else if (CurrentColor == LightColor.Red && _counter == _redDelay)
            {
                OnLightColorChanged(new LightColorChangedEventArgs(CurrentColor, LightColor.Yellow));
                _counter = 0;
            }
            else if (CurrentColor == LightColor.Yellow && _counter == _yellowDelay && _beforeColor == LightColor.Green)
            {
                OnLightColorChanged(new LightColorChangedEventArgs(CurrentColor, LightColor.Red));
                _counter = 0;
            }
            else if (CurrentColor == LightColor.Yellow && _counter == _yellowDelay && _beforeColor == LightColor.Red)
            {
                OnLightColorChanged(new LightColorChangedEventArgs(CurrentColor, LightColor.Green));
                _counter = 0;
            }
            else {
                //do nothing
            }
        }

        public LightColor CurrentColor { get; private set; }

        public event EventHandler<LightColorChangedEventArgs> LightColorChanged;

        protected void OnLightColorChanged(LightColorChangedEventArgs e)
        {
            _beforeColor = e.BeforeColor;
            CurrentColor = e.CurrentColor;
            if (LightColorChanged != null) //подписчики есть?
            {
                LightColorChanged(this, e);
            }
        }
    }
}
